package client_server_jpg;

import java.io.*;
import java.net.Socket;

public class Client {
    private static final String SERVER_HOST = "localhost";
    private static final int SERVER_PORT = 8899;
    private static final int BUFFER_SIZE = 1024;

    public static void main(String[] args) {
        try {
            sendImageToServer();
        } catch (IOException e) {
            // 更细致地处理异常或提供更丰富的错误信息
            e.printStackTrace();
        }
    }

    private static void sendImageToServer() throws IOException{
        // 创建Socket对象
        Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
        try (
            // 通过Socket获取输出流对象
            OutputStream out = socket.getOutputStream();
            FileInputStream fis = new FileInputStream("demo22\\resources\\01.png");
        ) {
            byte[] buf = new byte[BUFFER_SIZE];
            int len;
            // 读取图片文件并写入Socket输出流
            while ((len = fis.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            // 告知服务器这边已经写完了
            socket.shutdownOutput();

            // 从服务端接收到返回信息
            try (InputStream in = socket.getInputStream();
                 BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
                System.out.println(br.readLine());
            }
        } finally {
            // 尝试关闭Socket，即使在关闭输入/输出流时发生异常
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        }
    }
}
